package com.ldc.framework.activity

import android.content.Context
import android.content.Intent
import android.os.Message
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.listener.OnRowListener2
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.KeyboardUtils
import com.ldc.commonlibs.uts.MessageUts
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMActivity
import com.ldc.commonres.views.StateViewLayout
import com.ldc.framework.R
import com.ldc.framework.adapter.HotKeyAdapter
import com.ldc.framework.adapter.SearchAdapter
import com.ldc.framework.databinding.FrameworkActivitySearchBinding
import com.ldc.framework.model.ArticleModel
import com.ldc.framework.model.HotKeyModel
import com.ldc.framework.viewmodel.FrameworkViewModelBase
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

class SearchActivity : VBMActivity<FrameworkActivitySearchBinding, FrameworkViewModelBase>() {

    private var page: Int = 0
    private var searchAdapter: SearchAdapter? = null
    private var hotKeyAdapter: HotKeyAdapter? = null

    companion object {
        //
        private const val REFRESH_CODE = 0x1231

        //
        private const val ARG_KEY = "key"
        fun start(context: Context, key: String) {
            val it = Intent(context, SearchActivity::class.java).apply {
                putExtra(ARG_KEY, key)
            }
            context.startActivity(it)
        }
    }

    override fun processMessage(msg: Message): Boolean {
        when (msg.what) {
            REFRESH_CODE -> {
                val key: String = viewBind?.etSearch?.text.toString()
                getQueryKey(key)

            }
        }
        return super.processMessage(msg)
    }

    override fun main() {
        initHotKeyAdapter()
        initAdapter()

        viewBind?.let { vb ->
            vb.flBack.setOnClickListener { finish() }
            // 下拉刷新
            vb.rrv.refreshView.let {
                it.setEnableAutoLoadMore(true)
                it.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                    override fun onRefresh(refreshLayout: RefreshLayout) {
                        showContentView()
                        page = 0
                        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                    }

                    override fun onLoadMore(refreshLayout: RefreshLayout) {
                        page += 1
                        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                    }
                })
            }
            // 搜索事件
            vb.etSearch.setOnEditorActionListener { textView, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索要做的操作
                    page = 0
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }
                // 隐藏键盘
                KeyboardUtils.hideSoftInput(textView)
                false
            }
        }
        //
        hotKey()
        //
        MessageUts.sendMessage(getHandler(), REFRESH_CODE)

        //  点击刷新
        addOnReTryListener(object : OnRowListener<Int> {
            override fun onRow(v: View, data: Int) {
                page = 0
                MessageUts.sendMessage(getHandler(), REFRESH_CODE)
            }
        })

    }


    override fun initStateViewLayout(): StateViewLayout? {
        return StateViewLayout.Companion.init(this, R.id.rrv)
    }

    override fun createViewBinding(): FrameworkActivitySearchBinding =
        FrameworkActivitySearchBinding.inflate(layoutInflater)

    override fun createViewModel(): FrameworkViewModelBase =
        ViewModelUtils.create(this, FrameworkViewModelBase::class.java)

    private fun initHotKeyAdapter() {
        hotKeyAdapter = HotKeyAdapter().apply {
            addOnRowListener(object : OnRowListener<HotKeyModel> {
                override fun onRow(v: View, data: HotKeyModel) {
                    page = 0
                    viewBind?.etSearch?.setText(data.name)
                    getQueryKey(data.name)
                }
            })
        }
        viewBind?.let { vb ->
            vb.rvHotKey.let {
                it.adapter = hotKeyAdapter
                it.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
                it.setHasFixedSize(true)
            }
        }
    }


    private fun initAdapter() {
        searchAdapter = SearchAdapter().apply {
            //
            addCollectRowListener(object : OnRowListener2<ArticleModel, Int> {
                override fun onRow(v: View, data: ArticleModel, data2: Int) {
                    if (data.collect) {
                        // 取消收藏
                        viewModel?.uncollectOriginId("${data.id}")
                            ?.observe(this@SearchActivity) {
                                if (ApiUtils.isSuccess(it)) {
                                    searchAdapter?.changeDataItem(data2)
                                }
                            }
                    } else {
                        // 收藏
                        viewModel?.collect("${data.id}")?.observe(this@SearchActivity) {
                            if (ApiUtils.isSuccess(it)) {
                                searchAdapter?.changeDataItem(data2)
                            }
                        }
                    }
                }
            })
            addOnRowListener(object : OnRowListener<ArticleModel> {
                override fun onRow(v: View, data: ArticleModel) {
                    ARouter.getInstance()
                        .build(RouteConf.WebViewRoute.startEnter)
                        .withString(AppConf.ARG_TITLE, data.title)
                        .withString(AppConf.ARG_URL, data.link)
                        .navigation()
                }
            })
        }
        viewBind?.rrv?.rv?.recyclerview?.let {
            it.setHasFixedSize(true)
            it.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            it.adapter = searchAdapter
        }
    }


    //加载热词
    private fun hotKey() {
        viewModel?.hotkey()?.observe(this) {
            if (ApiUtils.isSuccess(it)) {
                hotKeyAdapter?.addNewData(it.data!!)
            }
        }
    }


    // 搜索
    private fun getQueryKey(str: String = "") {
        showLoadingView()
        viewModel?.queryKey(page, str)?.observe(this) { data ->
            showContentView()
            viewBind?.rrv?.refreshView?.let {
                if (it.state.isOpening) {
                    it.finishRefresh()
                    it.finishLoadMore()
                }
                it.setNoMoreData(page == data.data?.pageCount)
            }
            if (ApiUtils.isSuccess(data)) {
                if (page == 0 && data.data?.total == 0) {
                    showEmptyView()
                } else {
                    if (page > 0) {
                        searchAdapter?.addNewData(data.data?.datas)
                    } else {
                        searchAdapter?.newData(data.data?.datas)
                    }
                }
            } else {
                showErrorView()
            }
        }

    }

}